package com.qiguliuxing.dts.admin.controller;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.vo.DtsTopicVo;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsGoods;
import com.qiguliuxing.dts.db.domain.DtsGoodsProduct;
import com.qiguliuxing.dts.db.domain.DtsTopic;
import com.qiguliuxing.dts.service.base.DtsGoodsProductService;
import com.qiguliuxing.dts.service.base.DtsGoodsService;
import com.qiguliuxing.dts.service.base.DtsTopicService;
import com.qiguliuxing.dts.service.qcode.QCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import jodd.util.StringUtil;
import lombok.val;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/topic")
@Validated
@Api(tags = ApiAdminConsts.Topic.PARENT)
public class AdminTopicController {
	private static final Logger logger = LoggerFactory.getLogger(AdminTopicController.class);

	@Autowired
	private DtsTopicService topicService;

	@Autowired
	private DtsGoodsService dtsGoodsService;

	@Autowired
	private DtsGoodsProductService dtsGoodsProductService;

	@RequiresPermissions("admin:topic:list")
	@RequiresPermissionsDesc(menu = { "推广管理", "专题管理" }, button = "查询")
	@GetMapping("/list")
	@ApiOperation(value=ApiAdminConsts.Topic.LIST)
	@WebLog(description = ApiAdminConsts.Topic.LIST,excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "活动名称") String title,
					   @ApiParam(value = "子标题") String subtitle,
					   @ApiParam(value = "结束时间") @RequestParam(required = false) String startDate,
					   @ApiParam(value = "开始时间") @RequestParam(required = false) String endDate,
					   @ApiParam(value = "活动状态") @RequestParam(required = false) Byte state,
					   @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
					   @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {
		List<DtsTopic> topicList = topicService.querySelective(title, subtitle,startDate,endDate,state, page, limit, sort, order);
		List<DtsTopicVo> dtsTopicVos=new ArrayList<>();
		for (DtsTopic dtsTopic: topicList) {
			if(null!=dtsTopic.getGoods()){
				dtsTopic.setGoodNumber(dtsTopic.getGoods().length);
			}
			LocalDateTime addTime = dtsTopic.getAddTime();
			LocalDateTime endTime = dtsTopic.getEndTime();
			if (LocalDateTime.now().isBefore(addTime)) {
				dtsTopic.setState((byte) 1);
			}
			if (LocalDateTime.now().isAfter(addTime) && LocalDateTime.now().isBefore(endTime)) {
				dtsTopic.setState((byte) 2);
			}
			if (LocalDateTime.now().isAfter(endTime)) {
				dtsTopic.setState((byte) 3);
			}
			List<DtsGoods> dtsGoods=new ArrayList<>();
			DtsTopicVo dtsTopicVo=new DtsTopicVo();
			for (int i=0;i<dtsTopic.getGoods().length;i++){
				DtsGoods goodsSn = dtsGoodsService.findById(Integer.valueOf(dtsTopic.getGoods()[i].split("-")[0]));
				if(null!=goodsSn) {
					if (null != goodsSn.getId()) {
						List<DtsGoodsProduct> data = dtsGoodsProductService.queryByGid(goodsSn.getId());
						if (!data.isEmpty()) {
							int sums = 0;
							for (DtsGoodsProduct product : data) {
								sums += product.getNumber();
							}
							goodsSn.setSums(sums);
						}
					}
					dtsGoods.add(goodsSn);
				}
			}
			dtsTopicVo.setDtsTopic(dtsTopic);
			dtsTopicVo.setDtsGoods(dtsGoods);
			dtsTopicVos.add(dtsTopicVo);
		}
		long total = PageInfo.of(topicList).getTotal();
		Map<String, Object> data = new HashMap<>(2);
		data.put("total", total);
		data.put("items",dtsTopicVos);
		return ResponseUtils.ok(data);
	}

	private Object validate(DtsTopic topic) {
		String title = topic.getTitle();
		if (StringUtils.isEmpty(title)) {
			return ResponseUtils.badArgument();
		}
		return null;
	}

	@RequiresPermissions("admin:topic:create")
	@RequiresPermissionsDesc(menu = { "推广管理", "专题管理" }, button = "添加")
	@PostMapping("/create")
	@ApiOperation(value=ApiAdminConsts.Topic.CREATE)
	@WebLog(description = ApiAdminConsts.Topic.CREATE,persistence = true)
	public Object create(@RequestBody DtsTopic topic) {
		Object error = validate(topic);
		if (error != null) {
			return error;
		}
		topicService.add(topic);
	/*	String url = "http://videoshop.jszechao.com/?myId=".concat(String.valueOf(topic.getId()));
		topic.setShareUrl(url);
		topicService.updateById(topic);*/
		return ResponseUtils.ok(topic);
	}

	@RequiresPermissions("admin:topic:read")
	@RequiresPermissionsDesc(menu = { "推广管理", "专题管理" }, button = "详情")
	@GetMapping("/read")
	@ApiOperation(value=ApiAdminConsts.Topic.READ)
	@WebLog(description = ApiAdminConsts.Topic.READ)
	public Object read(@ApiParam(value = "专题id") @NotNull Integer id) {
		DtsTopic topic = topicService.findById(id);
		return ResponseUtils.ok(topic);
	}

	@RequiresPermissions("admin:topic:update")
	@RequiresPermissionsDesc(menu = { "推广管理", "专题管理" }, button = "编辑")
	@PostMapping("/update")
	@ApiOperation(value=ApiAdminConsts.Topic.UPDATE)
	@WebLog(description = ApiAdminConsts.Topic.UPDATE,persistence = true)
	public Object update(@RequestBody DtsTopic topic) {
		Object error = validate(topic);
		if (error != null) {
			return error;
		}
		if (topicService.updateById(topic) == 0) {
			logger.error("推广管理->专题管理->编辑 错误:{}", "更新数据失败!");
			return ResponseUtils.updatedDataFailed();
		}
		return ResponseUtils.ok(topic);
	}

	@RequiresPermissions("admin:topic:delete")
	@RequiresPermissionsDesc(menu = { "推广管理", "专题管理" }, button = "删除")
	@PostMapping("/delete")
	@ApiOperation(value=ApiAdminConsts.Topic.DELETE)
	@WebLog(description = ApiAdminConsts.Topic.DELETE,persistence = true)
	public Object delete(@RequestBody DtsTopic topic) {
		LocalDateTime addTime = topic.getAddTime();
		LocalDateTime endTime = topic.getEndTime();
		if (LocalDateTime.now().isAfter(addTime) && LocalDateTime.now().isBefore(endTime)) {
			return ResponseUtils.fail(-1,"活动正在进行中，不能删除");
		}
		topicService.deleteById(topic.getId());
		return ResponseUtils.ok();
	}

	@RequiresPermissions("admin:topic:putAway")
	@RequiresPermissionsDesc(menu = { "推广管理", "专题管理" }, button = "上架")
	@PostMapping("/putAway")
	@ApiOperation(value=ApiAdminConsts.Topic.DELETE)
	@WebLog(description = ApiAdminConsts.Topic.DELETE,persistence = true)
	public Object putAway(@ApiParam(value = "id")  Integer id) {
		if(!StringUtils.isEmpty(id)) {
			DtsTopic dtsTopic = topicService.findById(id);
			if(null!=dtsTopic) {
				dtsTopic.setIsOnShelves(true);
				topicService.update(dtsTopic);
				return ResponseUtils.ok();
			}
		}
		return ResponseUtils.fail();
	}

	@RequiresPermissions("admin:topic:outAway")
	@RequiresPermissionsDesc(menu = { "推广管理", "专题管理" }, button = "下架")
	@PostMapping("/outAway")
	@ApiOperation(value=ApiAdminConsts.Topic.DELETE)
	@WebLog(description = ApiAdminConsts.Topic.DELETE,persistence = true)
	public Object outAway(@ApiParam(value = "id")  Integer id) {
		if(!StringUtils.isEmpty(id)) {
			DtsTopic dtsTopic = topicService.findById(id);
			if(null!=dtsTopic) {
				dtsTopic.setIsOnShelves(false);
				topicService.update(dtsTopic);
				return ResponseUtils.ok();
			}
		}
		return ResponseUtils.fail();
	}

	@RequiresPermissions("admin:topic:check")
	@RequiresPermissionsDesc(menu = {"推广管理", "专题管理"}, button = "校验名称")
	@PostMapping("/checkName")
	public Object checkName(@RequestBody DtsTopic dtsTopic) {
		if (null != dtsTopic.getId()) {
			DtsTopic dtsTopic1 = topicService.findById(dtsTopic.getId());
			if (dtsTopic1.getTitle() == dtsTopic.getTitle()) {
				return ResponseUtils.fail(-1, "不存在重复名称");
			}
		} else {
			if (null != dtsTopic.getTitle()) {
				if (topicService.checkName(dtsTopic.getTitle()) > 0) {
					return ResponseUtils.ok("1", "存在重复名称");
				}
			}
		}
		return ResponseUtils.fail(-1, "不存在重复名称");
	}
}
